package leetcode;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-12-09 01:00
 **/
public class LeetCode794 {

    public boolean validTicTacToe(String[] board) {
        int xCount = 0;
        int oCount = 0;
        for (String str : board) {
            for (char c : str.toCharArray()) {
                xCount = c == 'X' ? xCount + 1 : xCount;
                oCount = c == 'O' ? oCount + 1 : oCount;
            }
        }

        if (oCount != xCount && xCount - oCount != 1) {
            return false;
        }

        if (win(board, 'X') && xCount - oCount != 1) {
            return false;
        }

        if (win(board, 'O') && xCount != oCount) {
            return false;
        }

        return true;
    }

    boolean win(String[] board, char c) {
        for (int i = 0; i < 3; i++) {
            if (board[i].charAt(0) == c && board[i].charAt(1) == c && board[i].charAt(2) == c) {
                return true;
            }
            if (board[0].charAt(0) == c && board[1].charAt(0) == c && board[2].charAt(0) == c) {
                return true;
            }
        }

        if (board[0].charAt(0) == c && board[1].charAt(1) == c && board[2].charAt(2) == c) {
            return true;
        }

        if (board[0].charAt(2) == c && board[1].charAt(1) == c && board[2].charAt(0) == c) {
            return true;
        }
        return false;
    }

}
